<template>
    <el-dialog title="编辑告警标签" :visible="visible" class="label-config-dialog" :destroy-on-close="true" width="550px" :before-close="() => $emit('update:visible',false)">
        <div class="tags-content" style="padding: 0 20px" v-loading="confirmLoading">
            <div class="tags-box" v-for="(tag, index) in tagList" :key="tag.lableId">
                <div :class="['input-wrapper', tag.active ? 'tags-active-wrapper ' : 'tags-wrapper ']" v-if="editable[index]">
                    <el-input
                        v-model.trim="tag.lableName"
                        :ref="'editableInput' + index"
                        size="small"
                        :style="'width:' + (tag.lableName.length * 12 + 45) + 'px;min-width:80px;font-size:12px'"
                        maxlength="10"
                    >
                        <span slot="suffix">
                            <i class="el-icon el-icon-circle-check" @click="editTagItem(tag, index)"></i>
                            <i class="el-icon el-icon-circle-close" @click="closeTagItem(tag, index)"></i>
                        </span>
                    </el-input>
                </div>

                <el-tag
                    v-else
                    :closable="!tag.active"
                    :class="['tag-item', tag.active ? 'active' : '']"
                    @click="singleClick(tag, index)"
                    @dblclick.native="doubleClick(tag, index)"
                    :disable-transitions="true"
                    @close="onDelete(tag.lableId)"
                >
                    {{ tag.lableName }}
                </el-tag>
            </div>

            <el-button class="btn" size="small" icon="el-icon-plus" @click="onAdd()" v-show="!showEdit && canAddTag">
                标签
            </el-button>
            <el-input v-show="showEdit" class="edit-box" placeholder="标签名称" v-model.trim="curEdit.lableName" maxlength="10" ref="editInput">
                <span slot="suffix">
                    <i class="el-icon el-icon-circle-check" @click="addTag"></i>
                    <i
                        class="el-icon el-icon-circle-close"
                        @click="
                            curEdit.canSubmit = 'Y'
                            curEdit.lableName = curEdit.oldTagName
                            showEdit = false
                        "
                    ></i>
                </span>
            </el-input>
        </div>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" v-hasPermi="['sys:config:tagdete']" @click="onSave" style="margin-right: 8px">确定</el-button>
            <el-button style="margin-left: 0px" @click="$emit('update:visible',false)">取消</el-button>
        </div>
    </el-dialog>
</template>
<script>
import { addLable, deleteLable, modifyLable, getAllLables, saveLableRelation, getLableByAlarm } from '@/api/modules/eventManagement/alarmLabel'
let timer = null
export default {
    props: {
        visible: {
            type: Boolean,
            default: false
        },
        orderData: {
            type: Object,
            default: {}
        }
    },
    data() {
        return {
            tagList: [],
            oldTagList: [],
            showEdit: false,
            canAddTag: true,
            curEdit: {},
            clickNum: 0,
            loading: false,
            confirmLoading: false,
            activeTags: [],
            editable: [],
            clickTimer: null
        }
    },
    watch: {
        visible(v) {
            if (v) {
                this.init()
            } else {
                this.showEdit = false
                this.curEdit = {}
                this.clickNum = 0
                this.tagList = []
            }
        }
    },
    methods: {
        async init() {
            this.editable = []
            this.confirmLoading = true
            this.activeTags = []
            await this.getActiveTags()
            await this.getMyAllLables()
        },
        /**
         * 获取当前事件选中标签
         */
        async getActiveTags() {
            let activeTagsResult = await getLableByAlarm(this.orderData.warningOrderId)
            if (activeTagsResult.code == 200) {
                this.activeTags = activeTagsResult.data
            }
        },
        /**
         * 获取所有标签信息
         */
        async getMyAllLables() {
            let res = await getAllLables()
            this.confirmLoading = false
            if (res.code == 200) {
                this.tagList = res.data.map((item) => {
                    item.active = false // 默认不选中
                    this.editable.push(false) // 默认输入框不显示
                    // 循环找出之前选中的标签
                    for (let i = 0; i < this.activeTags.length; i++) {
                        if (item.lableId === this.activeTags[i].lableId) {
                            item.active = true
                            break
                        }
                    }
                    return item
                })
                if (this.tagList.length >= 20) {
                    this.canAddTag = false
                }
            }
        },
        /**
         * 单击事件
         */
        singleClick(tag, index) {
            // 先清除上次执行的Timer
            clearTimeout(timer)
            // 利用Timer的时间间隔进行单击延时
            timer = setTimeout(() => {
                this.activeTags = []
                this.tagList.forEach((item) => {
                    if (item.lableId == tag.lableId) {
                        item.active = !item.active
                        this.$forceUpdate()
                    }
                    if (item.active) {
                        this.activeTags.push(item)
                    }
                })
            }, 300)
        },
        /**
         * 双击事件
         */
        doubleClick(tag, index) {
            clearTimeout(timer)
            if (this.showEdit) {
                $message.warning('请先保存标签')
                return
            }
            let editable = this.editable.filter((item) => item == true)
            if (editable.length > 0) {
                $message.warning('请先保存所修改的标签')
                return
            }
            this.$set(this.editable, index, true)
            this.curEdit = tag
            this.curEdit.oldTagName = tag.lableName
            this.curEdit.canSubmit = 'N'
            this.$nextTick(() => {
                let editableInput = 'editableInput' + index
                this.$refs[editableInput][0].$refs.input.focus()
            })
        },
        /**
         * 选中标签
         * @param tag 对应tag对象（lableId,lableName）
         * @param index 索引
         */
        onSelect(tag, index) {
            this.clickNum += 1
            setTimeout(() => {
                if (this.clickNum == 1) {
                    this.activeTags = []
                    this.tagList.forEach((item) => {
                        if (item.lableId == tag.lableId) {
                            item.active = !item.active
                            this.$forceUpdate()
                        }
                        if (item.active) {
                            this.activeTags.push(item)
                        }
                    })
                } else {
                    let editable = this.editable.filter((item) => item == true)
                    if (editable.length > 0) {
                        $message.warning('请先保存所修改的标签')
                        return
                    }
                    this.$set(this.editable, index, true)
                    this.curEdit = tag
                    this.curEdit.oldTagName = tag.lableName
                    this.curEdit.canSubmit = 'N'
                    this.$nextTick(() => {
                        let editableInput = 'editableInput' + index
                        this.$refs[editableInput][0].$refs.input.focus()
                    })
                }
                this.clickNum = 0
            }, 300)
        },
        /**
         * 删除标签
         * @param lableId 标签Id
         */
        onDelete(lableId) {
            deleteLable({ lableId }).then((res) => {
                if (res.code == 200) {
                    this.tagList.splice(
                        this.tagList.findIndex((item) => item.lableId == lableId),
                        1
                    )
                    this.curEdit.canSubmit = 'Y'
                    this.curEdit.lableName = this.curEdit.oldTagName
                    this.showEdit = false
                    if (this.tagList.length < 20) {
                        this.canAddTag = true
                    }
                } else {
                    return $message.warning(res.msg)
                }
            })
        },
        /**
         * 提交关联标签信息
         */
        async onSave() {
            if (this.curEdit && this.curEdit.canSubmit == 'N') {
                this.$refs.editInput.focus()
                return $message.warning('您编辑了标签，请先提交标签修改')
            }
            this.confirmLoading = true
            let params = {
                waringOrderId: this.orderData.warningOrderId,
                lables: this.tagList.filter((item) => item.active).map((item) => ({ lableId: item.lableId, lableName: item.lableName }))
            }
            let saveLableResult = await saveLableRelation(params)
            if (saveLableResult.code === 200) {
                $message.success(saveLableResult.msg)
                this.confirmLoading = false
                let activeTags = []
                let activeTagsResult = await getLableByAlarm(this.orderData.warningOrderId)
                if (activeTagsResult.code == 200) {
                    activeTags = activeTagsResult.data
                }
                this.$set(this.orderData,'alarmLableRelDTOS',activeTags)
                this.$emit('update:visible',false)
            }
        },
        /**
         * 点击新增标签
         */
        onAdd() {
            if (this.tagList >= 20) {
                return $message.warning('标签最多可支持20个')
            }
            let editable = this.editable.filter((item) => item == true)
            if (editable.length > 0) {
                $message.warning('请先保存所修改的标签')
                return
            }
            this.curEdit = { lableName: '' }
            this.showEdit = true
            this.curEdit.canSubmit = 'N'
            setTimeout(() => {
                this.$refs.editInput.focus()
            }, 100)
        },
        /**
         * 编辑标签
         * @param tag 对应tag对象（lableId,lableName）
         * @param index 索引
         */
        async editTagItem(tag, index) {
            if (!this.checkTagItem(tag)) {
              return
            }
            console.log(this.curEdit.oldTagName, tag, '????')
            if (this.curEdit.oldTagName === tag.lableName) {
                this.$set(this.editable, index, false)
                await this.getMyAllLables()
                this.showEdit = false
                this.curEdit.canSubmit = 'Y'
                if (this.tagList.length >= 20) {
                    this.canAddTag = false
                }
                return $message.success('修改成功')
            }
            let params = {
                lableName: tag.lableName,
                lableId: tag.lableId
            }
            let res = await modifyLable(params)
            if (res.code == 200) {
                this.$set(this.editable, index, false)
                await this.getMyAllLables()
                this.showEdit = false
                this.curEdit.canSubmit = 'Y'
                if (this.tagList.length >= 20) {
                    this.canAddTag = false
                }
                $message.success(res.msg)
            } else {
                this.$refs.editInput.focus()
                $message.warning(res.msg)
            }
        },
        /**
         * 编辑标签，新增入参校验
         */
        checkTagItem(tag) {
            if (!tag.lableName) {
                $message.warning('标签名称不能为空')
                return false
            }
            let repeatTag = this.tagList.filter((item) => {
                if (item.lableName === tag.lableName && item.lableId !== tag.lableId) {
                    return item
                }
            })
            if (repeatTag.length > 0) {
                $message.warning('标签名称重复，无法添加！')
                return false
            }
            return true
        },
        /**
         * 增加标签
         */
        async addTag() {
            if (!this.checkTagItem(this.curEdit)) {
              return
            }
            let params = {
                lableName: this.curEdit.lableName,
                lableId: this.curEdit.lableId
            }
            let res = await addLable(params)
            if (res.code == 200) {
                await this.getMyAllLables()
                this.showEdit = false
                this.curEdit.canSubmit = 'Y'
                if (this.tagList.length >= 20) {
                    this.canAddTag = false
                }
                $message.success(res.msg)
            } else {
                this.$refs.editInput.focus()
                $message.warning(res.msg)
            }
        },
        /**
         * 关闭对应标签input
         * @param tag 对应tag对象（lableId,lableName）
         * @param index 索引
         */
        closeTagItem(tag, index) {
            this.curEdit.canSubmit = 'Y'
            tag.lableName = this.curEdit.oldTagName
            this.$set(this.editable, index, false)
        }
    }
}
</script>
<style lang="scss" scoped>
.label-config-dialog {
    .edit-box {
        display: inline-block;
        width: 150px;
        .el-icon {
            font-size: 12px;
            cursor: pointer;
            position: relative;
            top: 2px;
        }
    }
    .tag-item {
        margin: 0 16px 8px 0;
        height: 22px;
        line-height: 22px;
        user-select: none;
        display: inline-flex;
        justify-content: center;
        align-items: center;
        font-size: 12px;
        border-radius: 2px;
        background: rgba(0, 0, 0, 0.04);
        color: rgba(0, 0, 0, 0.65);
        border: 1px solid rgba(0, 0, 0, 0.15);
    }
    .active {
        background: #fff1f0;
        border: 1px solid #ffa39e;
        color: #ff4d4f;
        padding-right: 24px;
    }
    .btn {
        height: 22px;
        line-height: 22px;
        padding: 0 16px;
        margin-right: 8px;
        background: #ffffff;
        border-radius: 2px;
        border: 1px dashed rgba(0, 0, 0, 0.15);
        user-select: none;
        display: inline-flex;
        justify-content: center;
        align-items: center;
    }
    .bd2 {
        height: 22px;
        font-size: 14px;
    }
    /deep/.el-icon-close {
        color: rgba(0, 0, 0, 0.65);
        line-height: 17px;
    }
    /deep/.el-tag .el-tag__close:hover {
        color: #fff;
        background: rgba(0, 0, 0, 0.65);
        line-height: 17px;
    }
    .tagsFormItem >>> .el-tag .el-icon-close::before {
        display: none;
    }
    .tagsFormItem >>> .el-tag:hover .el-icon-close::before {
        display: block;
    }
}

/deep/ .el-dialog > .el-dialog__body {
    padding: 40px !important;
}
/deep/.el-input--suffix input {
    height: 20px;
}
/deep/.el-tag {
    border-radius: 2px !important;
}
.label {
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #000;
    opacity: 0.85;
    line-height: 22px;
    min-width: 100px;
}
.value {
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #333333;
    line-height: 20px;
}
.title {
    display: flex;
    align-items: center;
    flex-wrap: nowrap;
    margin-bottom: 18px;
}
.all-tags {
    position: relative;
    display: flex;
    flex-wrap: wrap;
}
.tag-tips {
    position: absolute;
    top: 0;
    left: 0;
}
/deep/.el-input--suffix .el-input__inner {
    padding-right: 35px !important;
    height: 22px !important;
    padding-left: 8px;
}
/deep/.edit-box .el-input__suffix {
    top: 2px !important;
}
/deep/.el-tag .el-icon-close {
    top: 0;
}
.tags-content {
    display: flex;
    flex-wrap: wrap;
}
.tags-box {
    /deep/ input {
        outline: none;
        border: none;
        background: transparent;
    }
}
.input-wrapper {
    margin: 0 16px 8px 0;
    height: 22px;
    line-height: 22px;
    user-select: none;
    display: inline-flex;
    justify-content: center;
    align-items: center;
    font-size: 12px;
    border-radius: 2px;
}
.tags-wrapper {
    background: rgba(0, 0, 0, 0.04);
    color: rgba(0, 0, 0, 0.65);
    border: 1px solid rgba(0, 0, 0, 0.15);
}
.tags-active-wrapper {
    background: #fff1f0;
    border: 1px solid #ffa39e;
    color: #ff4d4f;
}
</style>
